package com.dnndo.framework.web.service;

import com.dnndo.common.constant.RoleConstants;
import com.dnndo.common.core.domain.entity.SysRole;
import com.dnndo.common.core.domain.entity.SysUser;
import com.dnndo.common.exception.CustomExceptions;
import com.dnndo.system.service.IMenuService;
import com.dnndo.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户权限处理
 * 
 * @author ruoyi
 */
@Component
public class SysPermissionService
{
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private IMenuService menuService;

    /**
     * 获取角色数据权限
     * 
     * @param user 用户信息
     * @return 角色权限信息
     */
    public Set<String> getRolePermission(SysUser user)
    {
        Set<String> roles = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin())
        {
            roles.add("admin");
        }
        else
        {
            roles.addAll(roleService.selectRolePermissionByUserId(user.getUserId()));
        }
        return roles;
    }

    /**
     * 获取菜单数据权限
     * 
     * @param user 用户信息
     * @return 菜单权限信息
     */
    //已完成 多数据源查询区分
    public Set<String> getMenuPermission(SysUser user)
    {
        Set<String> perms = new HashSet<>();
        List<SysRole> roles = user.getRoles();
        if (!CollectionUtils.isEmpty(roles)) {
            for (SysRole role : roles) {
                Set<String> permsByRole = menuService.getPermsByRole(role);
                role.setPermissions(permsByRole);
                perms.addAll(permsByRole);
                //如果是超级管理员就跳出循环
                if (role.getRoleType().equals(RoleConstants.ROLE_TYPE_SUPER_ADMIN)) {
                    break;
                }
            }
        }
        if (CollectionUtils.isEmpty(perms)) {
            throw new CustomExceptions("用户没有权限",403);
        }
        return perms;
    }
}
